import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';

import { LoggerService } from '../logger/logger.service';
import { getReqMainInfo } from '../middleware/utils';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(@Inject(LoggerService) private readonly logger: LoggerService) {}

  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();
    const request = ctx.getRequest<FastifyRequest>();

    const message = exception.message || '';

    const req = getReqMainInfo(request);

    this.logger.error(message, {
      req,
      stack: exception.stack,
    });
    // 非 HTTP 标准异常的处理。
    response.status(HttpStatus.INTERNAL_SERVER_ERROR).send({
      errcode: '5000',
      errmsg: message,
    });
  }
}
